<?php
class Acl_PPMIS extends Zend_Acl
{
	
	 /**
	 * Contructor
	 *
	 * @return void
	 */
	public function __construct()
	{
		$this->addProjectRoles();
		$this->addProjectResources();

        /*$id   = $this->getIdentity();
        $role = $this->getUserRole();
		
		 $this->addRole(new Zend_Acl_Role($id), $role);*/
        foreach ($this->getPermissions() as $perm) {
            $this->allow($perm['role'], null, $perm['privilege']);
        }
	}
	
	public function addProjectRoles()
	{
		$projectRole = new ProjectRole();
		$prevRole = "";
		$allProjectRole = $projectRole-> getAllProjectRoles();
		//print_r($allProjectRole);
		foreach ($allProjectRole as $projectRole) {
			if ($prevRole == "") {
				$prevRole = "anonymous";
				$this->addRole(new Zend_Acl_Role($prevRole));
				$this->addRole(new Zend_Acl_Role($projectRole['name']),$prevRole);
				$prevRole = $projectRole['name'];
			} else {
				$this->addRole(new Zend_Acl_Role($projectRole['name']),$prevRole);
				$prevRole = $projectRole['name'];
			}
		}	
	}
	
	public function addProjectResources()
	{
		$permissions = new Permissions();
		$allPermissions = $permissions->getAllPermissions();
		foreach ($allPermissions as $permission) {
			$this->add(new Zend_Acl_Resource($permission['name']));
		}
	}
	
	public function getPermissions()
	{
		$schemePermissions = new SchemePermissions();
		return $schemePermissions->getSchemePermissions();
	}
	
	/**
     * Retrieve user role
     *
     * @return string
     */
    public function getUserRole()
    {
        /*$db = new Users();

        $role = $db->fetchRow($db->select('role')
            ->where('username = ?', $this->getIdentity())
        );

        if (!$role) {
            return 'anonymous';
        }

        return $role->role;*/

    }

    /**
     * Retrieve user identity
     *
     * @return string
     */
    public function getIdentity()
    {
        $auth = Zend_Auth::getInstance();

        if (!$auth->hasIdentity()) {
            return 'guest';
        }

        return $auth->username;
    }

}